<?php
namespace Home\Controller;
use Think\Controller;
use Org;
class BaseController extends Controller {

    protected $wxObj;

    public function _initialize()
    {
        if(!session("?openid")){
            import("Org.Wechat.wechat");
            if(stripos($_SERVER['HTTP_USER_AGENT'], 'micromessenger')==false){
                exit("请在微信端打开");
            }
            $callback="http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
            $config=M("wxConfig")->find(1);
            $this->wxObj=new \Org\Wechat\Wechat($config);
            $url=$this->wxObj->getOauthRedirect($callback,"sameCity","snsapi_userinfo");
            header("Location:".$url);
            if(isset($_GET['code'])){
                $json=$this->wxObj->getOauthAccessToken();
                $wx_user=$this->wxObj->getOauthUserinfo($json['access_token'],$json['openid']);
                $user=M("user")->where(array("openid"=>$json['openid']))->find();
                if($user){
                    M("user")->where(array("openid"=>$json['openid']))->save(array(
                        "nick_name"=>$wx_user['nickname'],
                        "headimg"=>$wx_user['headimgurl']
                    ));
                    $user=M("user")->where(array("openid"=>$json['openid']))->find();
                    session("user",$user);
                }else {
                    $id=M("user")->add(
                        array(
                            "openid"=>$json['openid'],
                            'nick_name'=>$wx_user['nickname'],
                            "headimg"=>$wx_user['headimgurl']
                        )
                    );
                    $user=M("user")->find($id);
                    session("user",$user);
//                  将新用户添加到积分表中
                    M('integral')->add(array(
                        "uid"=>$id,
                    ));
                    $this->signIn($id);
                }
                session("openid",$json['openid']);
            }

        }else{
            $this->signIn($_SESSION['user']['id']);
        }
    }


    /**
     * 校验信息并跳转到活动页
     * @param $func 跳转的方法名称
     */
    public function check($func){
        $user=session("user");
        $credit_money=100;//暂时设为诚信金缺省值
        if($user['mobile']==""){
            $this->error("发起活动需要通过手机验证",U("mobile/verify"));
        }
        if($user['positive_points']-$user['minus_points']>=$user['level_points']&&$user['frozen_money']<$credit_money){
            $this->error("您因被多次差评，继续发起活动需要冻结诚信金XXXX金。请勤做任务，提升信用哦",U("verify/checkpoints"));
        }
        $this->$func();
    }

    /**
     * 同意冻结金额并跳转到发起页面
     * @param $func 跳转的方法名称
     */
    public function frozenMoney($func){
        $user=session("user");
        $credit_money=100;//暂时设为诚信金缺省值
        if($user['remain_money']>=$credit_money){
            M("user")->where(array("id"=>$user['id']))->setDec("remain_money",$credit_money);
            M("user")->where(array("id"=>$user['id']))->setInc("frozen_money",$credit_money);
            $this->assign('frozen_money',$credit_money);
            $this->$func();
        }else {
            $this->error("余额不足，请充值",U("充值页面"));
        }

    }
    /**
     * 冻结余额
     * return 1 冻结成功
     * 0 余额不足
     */
    public function CheckBlance($needMoney=null,$user_id=null){
        if(!$user_id){
            $user_id=session('user.id');
        }
        $remain_money=M('user')->where('id='.$user_id)->getField('remain_money');
        // print_r($remain_money);
        // print_r($needMoney);
        if($remain_money<$needMoney){
            return 0;
        }else{
             M("user")->where(array("id"=>$user['id']))->setDec("remain_money",$needMoney);
             M("user")->where(array("id"=>$user['id']))->setInc("frozen_money",$needMoney);
             return 1;
        }
    }
    /**
     * 验证信用
     *  1 信用通过
     *  0 信用低
     */
    public function CheckCredit($user_id=null){
        if(!$user_id){
            $user_id=session('user.id');
        }
        // 验证用户信用
        $detail=M('user')->where('id='.$user_id)->find();
        // 信用校验标准：用户所得负分大于或等于当前等级分，则不可通过
        // 如：正分100分，负分50分，则等级分为100-50=50 负分=等级分，不能通过校验  
        if($detail) {
            if($detail['minus_points']>=$detail['positive_points']-$detail['minus_points']){
                return 0;
            }else{
                return 1;
            }
        }
    }
    /**
     * 验证是否注册
     * 1 注册过
     * 0 未注册
     */
    public function  CheckMobile($user_id){
        if(!$user_id){
            $user_id=session('user.id');
        }
        $mobile=M('user')->where('is='.$user_id)->getField('mobile');
        if($mobile){
            return 1;
        }else{
            return 0;
        }
    }
    /**
     * jssdk图片上传
     */
    public function saveImg($pic,$Controller='IHave') {
        //判断文件夹以及路径是否存在
        if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/Uploads') || !is_dir($_SERVER['DOCUMENT_ROOT'] . '/Uploads')) {
            //不存在就创建文件夹
            mkdir($_SERVER['DOCUMENT_ROOT'] . '/Uploads',511);
        };
        //判断子文件夹vote以及路径是否存在
        $firstLetterDir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/'.$Controller.'';
        if (!file_exists($firstLetterDir) || !is_dir($firstLetterDir)) {
            //不存在就创建子文件夹
            mkdir($firstLetterDir, 511);
        }

        //以日期为文件夹命名
        $sub_dir = date('Ymd');
        $firstLetterDir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/'.$Controller.'/' . $sub_dir;
        //判断子文件夹$sub_dir以及路径是否存在
        if (!file_exists($firstLetterDir) || !is_dir($firstLetterDir)) {
            mkdir($firstLetterDir, 511);
        }

        //下面开始上传文件到服务器
        //文件名
        foreach($pic as $k=>$v){
            $file_name = date('YmdHis') . '_' . rand(10000, 99999) . '.jpg';
            //文件真实路径
            $pic_wall_save_path = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/'.$Controller.'/' . $sub_dir . '/' . $file_name;
            //文件存到数据库的路径
            //            $file_web_path = C('site_url') . '/Uploads/editorNew/' . $sub_dir . '/' . $file_name;
            //获取文件内容
            // $json=$this->wxObj->getOauthAccessToken();
            // 调用Message控制器的get_access_token方法获取access_token
            $accessToken = $this->get_accessToken();
            $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=' . $accessToken . '&media_id=' . $v;
            //把文件内容转化为字符串
            $imgdata = file_get_contents($url);
            //打开指定文件
            file_put_contents($pic_wall_save_path,$imgdata);
            $new_img[] = '/Uploads/'.$Controller.'/' . $sub_dir . '/' . $file_name;
        }
        return $new_img;
    }

    /*
     * 获取access_token
     */
    function get_accessToken(){

        $tokenFile = "__ROOT__/access_token.txt"; // 缓存文件名

        $data = json_decode(file_get_contents($tokenFile)); //转换为json格式

        if ($data->expire_time < time() or ! $data->expire_time) {

            //token过期的情况

            $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . 'wx039966c14e8e98c4' . '&secret=' . '22d4e70060a2b225544cb3d19a519358');

            $res = json_decode($res, true); // 对 JSON 格式的字符串进行编码

            $access_token = $res['access_token'];

            if ($access_token) {

                $data['expire_time'] = time() + 3600; //保存1小时

                $data['access_token'] = $access_token;

                $fp = fopen($tokenFile, "w"); //只写文件

                fwrite($fp, json_encode($data)); //写入json格式文件

                fclose($fp); //关闭连接

            }

        } else {

            $access_token = $data->access_token;

        }

        return $access_token;

    }
    /**
     * 套餐查询
     * @param  [string]     $package_type     [套餐/单品]
     * @param  [array]      $city             [城市]
     * @param  [string]     $keyword          [查询关键字] 
     * @param  [string]     $belong_type      [套餐的所属分类] 
     */
    public function packageSearch(){
        $destination_type=I('post.destination_type');
        $destination=I('post.destination');
        $use_type=I('post.use_type');
        $keyword=I('post.gjc');
        $con_type=I('post.con_type');
        $user=session('user');
//        print_r(I('post.'));exit;
        // $res=D('ICan')->contentList($con_type,1,1,$keyword,$use_type);
         //位置筛选条件
        if($destination_type!=2){
            if($destination){
                $where['city']=$destination;
            }
        }
        if($use_type){
            $where['belong_type']=$use_type;
        }
        if($keyword){
            $where['set_meal']=array("like","%{$keyword}%");
        }
        if($con_type==0){
            //单品需要单品列表在商家下面
            $apply_list=M('i_have_apply')->select();
            foreach ($apply_list as $k => $v) {
                $apply_list[$k]['shop_background']=current(unserialize($v['shop_background']));
                $single_list=M("i_have_single")->where(array("apply_id"=>$v['id']))->select();
                if($distance=A('IWant')->getDistance($user['lat'],$user['lng'],$v['lat'],$v['lng'])){
                     $apply_list[$k]['distance']=$distance;
                }else{
                     $apply_list[$k]['distance']=0;
                }
                $apply_list[$k]['level']=M("user")->where(array("id"=>$v['user_id']))->getField("level");
                $apply_list[$k]['list']=$single_list;
                $apply_list[$k]['type']='single';
            }

        }else if($package_type==1){
            // 套餐
            $apply_list=M('i_have_package')->join('i_have_apply on i_have_package.apply_id=i_have_apply.id')->select();
        }
        // print_r($apply_list);die;
         $this->ajaxReturn($apply_list);
        // echo json_encode($apply_list);die;
 
    }
    /**
     * 递归寻找子级分类
     */
    public function getSon($data,$class_id){
        $temp = array();
//		p($class_id);
        //循环所有数据
        foreach ($data as $v) {
            //如果找到当前分类的子集
            if($v['belong_id'] == $class_id){
                //压入到临时数组
                $temp[] = $v['id'];
                //递归调用不断合并
                $temp = array_merge($temp,$this->getSon($data, $v['id']));
            }
        }
        //得到最终结果，返出
        return $temp;
    }
    /**
     * [存储未读消息并发送模板消息]
     * @param  [string]     $uid         [接收人]
     * @param  [string]     $content     [内容] 
     * @param  [string]     $name        [处理页面按钮名称] 
     * @param  [string]     $btn_type    [按钮类型 0 跳转 1执行方法 ]  
     * @param  [string]     $action      [执行的操作 如跳转就是url 执行方法就是方法名]  
     * @param  [string]     $type        [模板消息类型]   
     * @return empty
     */
     public function SaveSendMsg($uid,$content,$name,$btn_type,$action,$type,$template_type=0){
        $openid=M('user')->where('id='.$uid)->getField('openid');
        $logdata=array(
            'uid'=>$uid,
            'openid'=>$openid,
            'template_type'=>$template_type,
            'content'=>$content,
            'name'=>$name,
            'btn_type'=>$btn_type,//0 跳转 1执行方法 2.。。
            'action'=>$action,
        );
         //存一条未读消息
        $id=R('Message/SaveNoReadMessage',array('data'=>$logdata));
        if($id){
             // 发送模板消息
            $detail=array(
                'first'=>'您有新的未读消息，点击查看',
                'time'=>date('Y-m-d H:i:s',time()),
                'detail'=>$content,
                'uid'=>session('user.id'),
                'openid'=>session('user.openid'),
            );
            $url=C('home_url').'/Message/MessageDetail/m_id/'.$id.'.html';
            $res=R('Message/sendMsg',array('touser'=>$openid,'url'=>$url,'detail'=>$detail,'type'=>$type));
            return $res;
        }
       
     }
     /**
      * 生成随机暗号存入对应表中
     * @param  [string]     $table   [表名]  
     * @param  [string]     $id      [数据id]  
     * @param  [string]     $code    [存储暗号的字段名]   
      */
     public function generateSaveSignal($table,$id,$code='signal'){
        $num=rand(1000,9999);
        if(M($table)->where('id='.$id)->setField($code,$num)){
            return $num;
        }else{
            return false;
        }
     }
      /**
      * 生成活动编码存入对应表中 //编码格式-
     * @param  [string]     $table   [表名]  
     * @param  [string]     $id      [数据id]  
     * @param  [string]     $code    [存储编码的字段名]   
      */
     public function generateSaveCode($table,$id,$code='code'){
        $num=strtoupper(uniqid(15));
        if(M($table)->where('id='.$id)->setField($code,$num)){
            return $num;
        }else{
            return false;
        }
     }

    /*
    * 签到验证
    */
    public function signIn($uid){
        $where['id'] = $uid;
        $data = M('user')->where($where)->find();
        $day1 = $data['last_time'];
        $day1 = date('Y-m-d',$day1);
        $day2 = date('Y-m-d');

        //相差天数$diff
        $diff = $this->diffBetweenTwoDays($day1,$day2);
        $data['last_time'] = time();
        if($diff == 1){
//            连续登陆
            $data['sign_days'] += 1;
            $this->daysIntegral($diff);
        }else{
            if($diff>1){
                $data['sign_days'] = 1;
                if($diff>10){
                    $data['sign_days'] = 1;
                    $this->daysIntegral($diff);
                }
            }
        }
        M('user')->where($where)->save($data);
        return true;
    }

    /**
     * 算登录积分
     * @param $diff    超过1天用户没登录
     * @param $symbol  算加减$diff
     */
    public function daysIntegral($diff){
        $uid = $_SESSION['user']['id'];
        $where['id'] = $uid;
        $data = M('user')->where($where)->find();
        $landing =  M('landing')->select();
//        $landing = M('')
//        判断是(1)加积分还是(0)减积分
        if($diff <= 1){

            foreach($landing as $k=>$v){
                if($data['sign_days']>=$landing[$k]['low'] && $data['sign_days']<=$landing[$k]['high']){
                    M('user')->where(array('id'=>$uid))->setInc('positive_points',$v['num']);
                }
            }
        }elseif($diff > 10){
            M('user')->where(array('uid'=>$uid))->setInc('minus_points',($diff-10));
        }
        return true;
    }

    /**
     * 计算点赞的积分
     * @param string $show_id 当前文章id
     */
    public function praise($show_id){

        $todayBegin = mktime(0,0,0,date('m'),date('d'),date('Y'));
//        通过文章id找到用户id
        $uid = M('i_show_release')->where(array('show_id'=>$show_id))->getField('show_uid');
//        此用户在当天共有多少个赞
        $show['show_id'] = $uid;
        $show['create_time'] = array('like',$todayBegin.'%');
        $allOn = M('i_show_praise')->where($show)->count('show_praise');
        $where['id'] = $uid;
        if($allOn<=50){
//                每个赞是0.2分
            M('user')->where($where)->setInc('positive_points',0.2);
        }

        return true;
    }

    /**
     * 积分计算我踩
     * @param $show_id  踩的文章id
     *
     */
    public function praiseOn($show_id){
        $uid = M('i_show_release')->where(array('show_id'=>$show_id))->getField('show_uid');
//        踩一下用户积分自动减一
        M('user')->where(array('id'=>$uid))->setInc('minus_points',0.5);
        return true;
    }

    /**
     * 积分计算被评论人当天获得的评论数
     * @param $buid  被评论者的id
     * @return bool
     */
    public function commentIntegral($uid){

        $todayBegin = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $where['cuid'] = $uid;
        $where['time'] = array('like',$todayBegin.'%');
        $count = M('i_comment')->where($where)->count('comment_id');
        if($count<=20){
//                每个评论0.5分
            M('user')->where(array('id'=>$uid))->setInc('positive_points',0.5);
        }
        return true;
    }

    /**
     * 计算动态积分
     * @param $uid
     */
    public function dynameicIntegral($uid){
        $todayBegin = mktime(0,0,0,date('d'),date('m'),date('Y'));
        $where['show_uid'] = $uid;
        $where['show_time'] = array('like',$todayBegin.'%');
        $count = M('i_show_release')->where($where)->count('show_id');
        if($count<=10){
            //                每个动态1分
            M('user')->where(array('id'=>$uid))->setInc('positive_points',1);
        }
        return true;
    }

    /**
     * 计算积分发布活动
     * @param $uid   发布活动的用户id
     */
    public function publishActive($uid){
        $todayBegin = mktime(0,0,0,date('d'),date('m'),date('Y'));
        $where['uid'] = $uid;
        $where['end_time'] = array('like',$todayBegin.'%');
        $count = M('i_want')->where($where)->count('id');
        if($count<=5){
//            每个发布活动算1分
            M('user')->where(array('id'=>$uid))->setInc('positive_points',2);
        }
    }


    /**
     * 参加活动计算积分
     * @param $uid      参加活动人的uid
     * @param $uid      参加活动类型
     */
//    public function joinActive($uid,$type){
//        $todayBegin = mktime(0,0,0,date('d'),date('m'),date('Y'));
////        计算参加 i_can 我能
//        $where1['sign_user_id'] = $uid;
//        $where1['create_time']=array('like',$todayBegin.'%');
//        $where1['status'] = 1;
//        $count1 = M('i_can_sign')->where($where1)->count('id');
////        计算参加我要活动
//
//
//    }
    /**
     * 发起邀约
     * @param $uid   发布邀约的用户id
     */
    public function invitation($uid){
        $todayBegin = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $where['roximately_about_people'] = $uid;
        $where['roximately_time'] = array('like',$todayBegin.'%');
        $count = M('i_show_about')->where($where)->count('id');
        if($count<=50){
            M('user')->where(array('id'=>$uid))->setInc('positive_points',0.2);
        }
    }

    /**
     * 接受邀约
     */
    public function acceptIntitation(){

    }

    /**
     * 被邀约
     */
    public function beIntitation(){

    }
    /**
     * 获得星星评价
     * @param $uid  被评价人的 user_id
     * @param $uid  被评价人获得的星星评价
     */
      public function starIntegral($uid,$star){
          $todayBegin = mktime(0,0,0,date('m'),date('d'),date('Y'));
          $where['create_time'] = array('like',$todayBegin.'%');
          $where['uid'] = $uid;
          switch ($star)
          {
              case 5:
                  $count = M('this_table')->where($where)->count('5_star');
                  if($count<=5){
                      M('user')->where(array('id'=>$uid))->setInc('positive_points',2);
                  }
                  break;
              case 4:
                  $count = M('this_table')->where($where)->count('4_star');
                  if($count<=5){
                      M('user')->where(array('id'=>$uid))->setInc('positive_points',1);
                  }
                  break;
              case 3:
                  M('user')->where(array('id'=>$uid))->setInc('minus_points',1);
                  break;
              case 2:
                  M('user')->where(array('uid'=>$uid))->setInc('minus_points',3);
                  break;
              case 1:
                  M('user')->where(array('uid'=>$uid))->setInc('minus_points',5);
                  break;
          }
      }


    /**
     * @param $day1     数据表中的时间戳
     * @param $day2     现在的时间戳
     * @return float    返回二者的差
     */
    public function diffBetweenTwoDays ($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    /**
     * 违约活动扣50分，10个一星
     * @param $uid      违约uid
     * @param $active   活动类型
     */
    public function breakContractActive($uid,$active)
    {
        $data['uid'] = $uid;
        $data['create_time'] = time();
        $data['type'] = $active;
        $data['star'] = 1;
        for ($i = 1; $i <= 10; $i++) {
            M('star_credit')->add($data);
        }
        M('user')->where(array('id'=>$uid))->setInc('minus_points',50);
    }

    public function attention($uid,$relation_id){
        $todayBegin = mktime(0,0,0,date('m'),date('d'),date('Y'));
//        锁定关注人
        $where1['uid'] = $uid;
        $where1['create_time'] = $todayBegin;
//        锁定被关注人
        $where2['relation_id'] = $relation_id;
        $where2['create_time'] = $todayBegin;
//        计算当天关注人关注了多少
        $count1 = M('user_relation')->where($where1)->count('id');
//        计算当天被关注人被多少人关注
        $count2 = M('user_relation')->where($where2)->count('id');
        if($count1<=50){
            M('user')->where(array('id'=>$uid))->setInc('positive_points',0.2);
        }
        if($count2<=50){
            M('user')->where(array('id'=>$relation_id))->setInc('positive_points',0.2);
        }

        return true;
    }
    /**
     * 生成字母加数字的随机数
     *
     * @param $len 字符串长度
     * @param null $chars 字符串
     * @return string 生成的字符串
     */
    public function getRandomString($len, $chars=null)
    {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

}